
#include <BStyle>
#include <BHtmlItem>

#include "XmlTreeWidget.h"

XmlTreeWidget::XmlTreeWidget(BWidget* parent) : BTreeWidget(parent)
{

}
XmlTreeWidget::~XmlTreeWidget()
{

}

void XmlTreeWidget::reset(BXmlNode* xml)
{
	BTreeItem* rootItem = createTreeItem(xml);
	this->addItem(rootItem);
}

BTreeItem* XmlTreeWidget::createTreeItem(BXmlNode* node)
{
	if (node)
	{
		BString text = node->name();
		if (text.size())
		{
			text << '<';
			const BMap<BString, BString>& attribMap = node->attribMap();
			for (auto it = attribMap.begin(); it.valid(); ++it)
			{
				const BString& name = it.key();
				const BString& value = it.value();
				text << name << '=' << value << ' ';
			}
			text -= ' ';
			text << '>';
		}
		text << node->text();
		BTreeItem* item = new BTreeItem(text);
		if (dynamic_cast<BHtmlItem*>(node))
			item->setIcon(_htmlItemImage);
		else
			item->setIcon(_xmlNodeImage);
		item->setAsset(node);
		for (int i = 0; i < node->childCount(); i++)
		{
			BXmlNode* childNode = node->child(i);
			BTreeItem* childItem = createTreeItem(childNode);
			item->addChild(childItem);
		}
		return item;
	}
	return 0;
}

void XmlTreeWidget::styleEvent(const BEvent& event)
{
	if (const BStyle* style = this->realStyle())
	{
		_xmlNodeImage = style->icon("xml-node");
		_htmlItemImage = style->icon("html-item");
	}
}
